<template>
  <div class="variable-define">
    <div class="common-layout">
      <el-container>
        <el-main>
          <div class="transfer-container">
            <div>
              <el-transfer v-model="valueVarableKeys" filterable :titles="['值变量选择', '值变量']" :data="valueData"
                :props="{ key: 'value', label: 'label' }" @change="generateSql">
                <template #left-footer>
                  <el-button class="transfer-footer" size="small">Operation</el-button>
                </template>
              </el-transfer>
            </div>

            <div>
              <el-transfer v-model="conditionVarableKeys" filterable :titles="['条件变量选择', '条件变量']" :data="conditionData"
                :props="{ key: 'value', label: 'label' }" @change="generateSql"></el-transfer>
            </div>
          </div>
        </el-main>
        <el-footer>
          <div>
            <el-tabs v-model="activeTabName" v-loading="isLoading" class="demo-tabs" @tab-click="generateSql">
              <el-tab-pane label="查询SQL" name="SELECT">
                <el-scrollbar height="400px">
                  <TextAreaCopy :text="selSql" />
                </el-scrollbar>
              </el-tab-pane>
              <el-tab-pane label="修改SQL" name="UPDATE">
                <el-scrollbar height="400px">
                  <TextAreaCopy :text="updSql" />
                </el-scrollbar>
              </el-tab-pane>
              <el-tab-pane label="新增SQL" name="INSERT">
                <el-scrollbar height="400px">
                  <TextAreaCopy :text="insertSql" />
                </el-scrollbar>
              </el-tab-pane>
              <el-tab-pane label="删除SQL" name="DELETE">
                <el-scrollbar height="400px">
                  <TextAreaCopy :text="delSql" />
                </el-scrollbar>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-footer>
      </el-container>
    </div>
  </div>
</template>

<script>
import TextAreaCopy from './TextAreaCopy.vue';
export default {
  components: {
    TextAreaCopy
  },
  props: {
    excelData: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  watch: {
    excelData() {
      this.formatData();
    }
  },
  data() {
    return {
      valueVarableKeys: [],
      conditionVarableKeys: [],
      valueData: [],
      conditionData: [],
      activeTabName: 'SELECT',
      isLoading: false,
      selSql: 'SELECT * FROM table_name',
      updSql: 'UPDATE table_name SET ',
      delSql: 'DELETE FROM table_name',
      insertSql: 'INSERT INTO table_name'
    };
  },
  created() {
    this.formatData();
  },
  methods: {
    formatData() {
      this.valueVarableKeys = [];
      this.conditionVarableKeys = [];
      if (this.excelData.length > 0) {
        const variableList = Object.keys(this.excelData[0]) || [];
        this.valueData = variableList.map((item) => ({
          value: item,
          label: item
        }));
        this.conditionData = Array.from(this.valueData);
      }
    },
    async generateSql() {
      this.isLoading = true;
      try {
        await this.sleep(500);
        switch (this.activeTabName) {
          case 'SELECT':
            this.selSql = await this.generateSelectSql();
            break;
          case 'UPDATE':
            this.updSql = await this.generateUpdateSql();
            break;
          case 'INSERT':
            this.insertSql = await this.generateInsertSql();
            break;
          case 'DELETE':
            this.delSql = await this.generateDeleteSql();
            break;
          default:
            break;
        }
      } finally {
        this.isLoading = false;
      }
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async generateSelectSql() {
      let sql = 'SELECT ';
      sql += this.valueVarableKeys.length === 0 ? '*' : this.valueVarableKeys.join(',');
      sql += ' FROM table_name';

      if (this.conditionVarableKeys.length > 0) {
        const prefixSql = sql + ' WHERE ';
        sql = this.excelData.map(item => {
          return prefixSql + this.generateConditions(item);
        }).join(';\n');
      }
      sql += ';';
      return sql;
    },
    async generateUpdateSql() {
      if (this.valueVarableKeys.length === 0 || this.conditionVarableKeys.length === 0) return this.updSql;
      return this.excelData.map(item => {
        const setClause = this.valueVarableKeys.map(key => `${key}='${item[key]}'`).join(',');
        const whereClause = this.generateConditions(item);
        return `UPDATE table_name SET ${setClause} WHERE ${whereClause};`;
      }).join('\n');
    },
    async generateInsertSql() {
      if (this.valueVarableKeys.length === 0) return this.insertSql;
      return this.excelData.map(item => {
        const columns = this.valueVarableKeys.join(',');
        const values = this.valueVarableKeys.map(key => `'${item[key]}'`).join(',');
        return `INSERT INTO table_name (${columns}) VALUES (${values});`;
      }).join('\n');
    },
    async generateDeleteSql() {
      if (this.conditionVarableKeys.length === 0) return this.delSql;
      return this.excelData.map(item => {
        const whereClause = this.generateConditions(item);
        return `DELETE FROM table_name WHERE ${whereClause};`;
      }).join('\n');
    },
    generateConditions(item) {
      return this.conditionVarableKeys.map(key => `${key}='${item[key]}'`).join(' AND ');
    }
  }
};
</script>

<style scoped>
.el-transfer {
  max-width: 600px;
}

.transfer-container {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.button-container {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 20px;
}
</style>